﻿using Microsoft.Win32;

namespace Liang.Util.Register
{
    /// <summary>
    /// 注册表操作帮助类
    /// </summary>
    public class RegHelper
    {
        /// <summary>
        /// 打开注册表
        /// </summary>
        /// <param name="strSection">注册表路径</param>
        /// <param name="strKey">键</param>
        /// <param name="defaultValue">默认值</param>
        /// <returns></returns>
        public static object Open(string strSection, string strKey, object defaultValue)
        {
            object obj = defaultValue;
            RegistryKey rk = Registry.CurrentUser.OpenSubKey(strSection);
            if (null != rk)
            {
                obj = rk.GetValue(strKey);
                if (null == obj)
                {
                    obj = defaultValue;
                }
            }
            return obj;
        }

        /// <summary>
        /// 保存数据到注册表
        /// <para>若不存在指定的路径，则会创建</para>
        /// </summary>
        /// <param name="strSection">注册表路径</param>
        /// <param name="strKey">键</param>
        /// <param name="value">值</param>
        public static void Save(string strSection, string strKey, object value)
        {
            RegistryKey rk = Registry.CurrentUser.CreateSubKey(strSection);
            rk.SetValue(strKey, value);
        }

        /// <summary>
        /// 保存数据到注册表（二进制格式）
        /// </summary>
        /// <param name="strSection">注册表路径</param>
        /// <param name="strKey">键</param>
        /// <param name="value">值</param>
        public static void SaveBinary(string strSection, string strKey, object value)
        {
            RegistryKey rk = Registry.CurrentUser.CreateSubKey(strSection);
            rk.SetValue(strKey, value, RegistryValueKind.Binary);
        }

        /// <summary>
        /// 删除指定路径下的注册表
        /// </summary>
        /// <param name="strSection"></param>
        /// <param name="strKey"></param>
        public static void Delete(string strSection, string strKey)
        {
            RegistryKey software = Registry.LocalMachine.OpenSubKey(strSection, true);
            //删除
            software.DeleteValue(strKey);
            //关闭
            software.Close();
        }
    }
}
